package com.lucun.es_transaction.config;

import com.alibaba.fastjson.JSONObject;
import com.lucun.es_transaction.util.BaseException;
import com.lucun.es_transaction.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断状态
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //实例化
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //返回此处理程序方法的方法，也就是取得接口的方法
        Method method = handlerMethod.getMethod();
        //查看接口是否存在注释
        if (method.isAnnotationPresent(RolePermission.class)) {
            //取得接口的注解
            RolePermission annotation = method.getAnnotation(RolePermission.class);
            //获取login的访问权限，是登录完访问，还是不登录就可以访问
            if (!annotation.login()) {
                return true;
            }
        }
        //设置编码
        response.setCharacterEncoding("utf-8");
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        if (token != null) {
            //判断是否通过验证
            boolean result = JwtUtil.verify(token);
            //权限
            String role = JwtUtil.getRoleByToken(request);
            System.out.println(role);

            //查看接口是否存在注释
            if (method.isAnnotationPresent(RolePermission.class)) {
                //取得接口的注解
                RolePermission annotation = method.getAnnotation(RolePermission.class);
                //获取权限
                String roleRolePermission = annotation.role();
                if (StringUtils.isBlank(roleRolePermission)) {
                    throw new BaseException("接口权限获取失败");
                }
                //使用indexOf方法从头开始检索是否存在role,存在就返回位置,不存在就返回-1
                int i = roleRolePermission.indexOf(role);
                if (i == -1) {
                    throw new BaseException("用户权限不足");
                }
            }
            if (result) {
                System.out.println("通过拦截器");
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            JSONObject json = new JSONObject();
            json.put("success", "false");
            json.put("msg", "token认证失败，未通过拦截器");
            json.put("code", "50000");
            response.getWriter().append(json.toJSONString());
            System.out.println("token认证失败，未通过拦截器");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return true;
    }
}


